import random
import subprocess
import os
import time
from multiprocessing import Queue
from common.gene_log import Get_Time
from ppp_test import Ppp

def pre_exec():
    os.setpgid(0, 0)

class Ping_Test():

    def __init__(self):
        self.queue = Queue()
        self.stdout_pid = ""
        self.txt_name = Get_Time()
        self.Ppp = Ppp("/dev/ttyGSM2")
        self.web_list = ["39.156.69.79", "58.250.137.36", "123.126.55.41"]
        self.change_times = [i * 50 for i in range(0, 99999)]


    def ping(self):
        self.Ppp.start_ppp()
        a = 0
        b = 0
        c = 0
        err_count = 0
        restart = [i*800 for i in range(1,100)]

        ping_obj = subprocess.Popen("ping 39.156.69.79", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                                    bufsize=1, preexec_fn=pre_exec)


        while True:
            try:
                if c in self.change_times or ping_obj.stdout.readline(100) == b'':
                    x = random.randint(0, 2)
                    web_addr = self.web_list[x]
                    # print(web_addr)
                    ping_obj = subprocess.Popen("ping " + web_addr, shell=True, stdout=subprocess.PIPE,
                                                stderr=subprocess.STDOUT)

                c += 1

                # time.sleep(1)
                ppp_status = self.Ppp.check_status()

                status = ppp_status.stdout.readline(100)
                print("ppp statu: " + status.decode())
                with open("ppp_log/" + self.txt_name + ".txt", "a+") as f:
                    f.write("cmux_ppp_ping!!!")
                    f.write("ppp statu: " + status.decode())
                if status == b'not connected\n':
                    # ping_obj.terminate()
                    self.Ppp.start_ppp()
                    continue

                elif status == b'connecting\n':
                    print("拨号ing")
                    time.sleep(5)
                    continue

                else:

                    line = ping_obj.stdout.readline(100)
                    line = line.decode()
                    now_time = Get_Time()
                    print(now_time + "  >>>  " +line)

                    with open("ppp_log/" + self.txt_name + ".txt","a+") as f:
                        f.write(now_time + "  >>>  " +line)

                    if "ping: unknown host" in line:
                        # print("未知网络")
                        err_count += 1
                        b += 1
                        if err_count in restart:
                            print("错误次数过多，重新拨号！")
                            self.Ppp.stop_ppp()
                            continue

                        # if b == 2:
                        #     Ppp().stop_ppp()
                    elif "bytes of data" in line:
                        pass
                    elif "ping: sendmsg: Network is unreachable" in line:
                        # print("当前网络不可达")
                        err_count += 1
                        b += 1
                        if err_count in restart:
                            print("错误次数过多，重新拨号！")
                            self.Ppp.stop_ppp()
                            continue

                    elif line == '':
                        # print("当前line为空")
                        pass
                    else:
                        a += 1
                    cons = "当前ping成功了%d次，失败了%d次" % (a,b)
                    print(cons)
                    with open("ppp_log/" + self.txt_name + ".txt", "a+") as f:
                        f.write(cons+"\r\n")
                    continue
            except KeyboardInterrupt as e:
                # print(e)
                self.Ppp.stop_ppp()
                print("程序已关闭")
                break


